<?php
	$path = "../";
	include_once($path.'configuration.php');
	
	/*
	 * machine : 10.10.10.10
	 * type : 'ram'
	 * complement : '90%'
	 * action : 'add' | 'del'
	 */
	
	if(isset($_GET) && isset($_GET['action'])){
		extract($_GET);
		
		if($action == 'add'){
			//Ajout d'un incident
			if(isset($machine) && $machine != '' && isset($type) && $type != '' && isset($complement) && $complement != ''){
				
				$types = $dbh->getAllType_Incident();
				$exists = false;
				foreach($types as $val){
					if($val['nom_type'] == $type){
						$exists = true;
						$id_type = $val['id_type_incident'];
					}
				}
				
				if($exists == true){
					$type_inc = new Type_Incident($dbh, $id_type);
				}else{
					$type_inc = new Type_Incident($dbh);
					$type_inc->setName($type);
					$type_inc->save();
				}
				
				$mach = $dbh->getMachineByIP($machine);
				if($mach == 0){
					$incidents = array();
					$machmach = new machine($dbh);
					$machmach->setIp($machine);
					$machmach->setNom($machine);
					$machmach->save();
					$mach = $machmach->getId();
				}else{
					$incidents = $dbh->getAllIncidentByMachine($mach);
				}
				$exists = false;
				foreach($incidents as $incident){
					if($incident['type'] == $type_inc->getId()){
						$exists = true;
						$inc = new Incident($dbh, $incident['id_incident']);
						$inc->setComplement($complement);
						if($inc->save()){
							echo $inc->getId();
						}
					}
				}
				if($exists == false){
					//on ajoute un nouvel incident
					$incident = new Incident($dbh);
					$incident->setType($type_inc->getId());
					$incident->setIs_resolved('false');
					$incident->setMachine($mach);
					$incident->setComplement($complement);
					if($incident->save()){
						echo $incident->getId();
					}
				}
				
				
			}
		}elseif($action == 'del'){
			//Suppression d'un incident
			if(isset($id) && $id != ''){
				$inc = new Incident($dbh, $id);
				if($inc->delete()){
					echo true;
				}else{
					echo false;
				}
			}
		}
	}